package cn.gok.oa.interceptor;

import cn.gok.oa.system.entity.TbUser;
import cn.gok.oa.system.service.ITbUserService;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.JWTVerificationException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class JwtInterceptor extends InterceptorRegistry implements HandlerInterceptor {
    @Autowired
    private ITbUserService iTbUserService;

    public boolean preHandle(HttpServletRequest httpServletRequest,
                             HttpServletResponse httpServletResponse, Object object) throws Exception{

        //获取token
        String token = httpServletRequest.getHeader("token");
        // 如果不是映射到方法直接通过
        if(!(object instanceof HandlerMethod)){
            return true;
        }
        // 执行认证
        if (StrUtil.isBlank(token)) {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("code","1");
            jsonObject.put("msg","没有token，重新登陆");
            httpServletResponse.getWriter().print(jsonObject);
            throw new ServiceException("1","没有token，重新登陆");
        }

        //获取token的userid
        String userId;
        try {
            //解密获取
            userId = JWT.decode(token).getAudience().get(0); //得到token中的userid载荷
        } catch (JWTDecodeException j) {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("code","1");
            jsonObject.put("msg","token验证失败，重新登陆");
            httpServletResponse.getWriter().print(jsonObject);
            throw new ServiceException("1","token验证失败，重新登陆");
        }

        //根据userid查询数据库
        TbUser user = iTbUserService.getById(userId);

        if(user == null){
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("code","1");
            jsonObject.put("msg","token验证失败，重新登陆");
            httpServletResponse.getWriter().print(jsonObject);
            throw new ServiceException("1","token验证失败，重新登陆");
        }

        // 用户密码加签验证 token
        JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(user.getPassword())).build();
        try {
            jwtVerifier.verify(token);
        } catch (JWTVerificationException e) {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("code","1");
            jsonObject.put("msg","token验证失败，重新登陆");
            httpServletResponse.getWriter().print(jsonObject);
            throw new ServiceException("1","token验证失败，重新登陆");
        }

        return true;
    }
}

